package com.itsitio.registeradmin.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itsitio.registeradmin.web.UserContext;

public class UserContextFilter implements Filter {

	private List<String> allowedUriList = new ArrayList<String>();

	private static final Logger log = LoggerFactory.getLogger(UserContextFilter.class);
	 
	

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException {

		//System.out.println("======######################## UserContextFilter.doFilter()");

		HttpServletRequest requestHttp = (HttpServletRequest) request;
		HttpServletResponse responseHttp = (HttpServletResponse) response;
		HttpSession session = requestHttp.getSession(false);

		//String excludeURI = "showPortalStatisticHome.html";
		if (!this.allowedUriList.contains(requestHttp.getRequestURI())) {
			if (session == null) {
				if (log.isDebugEnabled())
					log.debug("The current user is not authenticated, session is null!");
				//hacemos un forward a la home page
				requestHttp.getRequestDispatcher("/index.html").forward(request, response);
				return;
			}

			UserContext currentUser = (UserContext) session.getAttribute("userContext");

			if (currentUser == null) {
				if (log.isDebugEnabled())
					log.debug("The current user is not authenticated, UserContext is null!");
				//hacemos un forward a la home page
				requestHttp.getRequestDispatcher("/index.html").forward(request, response);
				return;
			} 
			/*
			else {
				//TODO por el momento esto no se usa, dado que no estamos controlando roles ni authorizaciones.
				// Get relevant URI.
				String URI = ((HttpServletRequest) request).getRequestURI();

				// Obtain AuthorizationManager singleton from Spring
				// ApplicationContext.
				ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
				*
				 * AuthorizationManager authMgr =
				 * (AuthorizationManager)ctx.getBean("AuthorizatinManager");
				 * 
				 * //Invoke AuthorizationManager method to see if user can
				 * //access resource. boolean authorized =
				 * authMgr.isUserAuthorized(currentUser,URI); if (authorized) {
				 * filterchain.doFilter(request,response); } else {
				 * returnError(request
				 * ,response,"User is not authorized to access this area!"); }
				 *
			} */
		}

		// si llegamos hasta aqui, es porque el usuario esta autenticado, o bien es
		// una pagina que puede ser mostrada sin que el usuario este autenticado
		filterchain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {

		// Get init parameter
		String allowedUri = config.getInitParameter("allowedUriList");
		
		//System.out.println("==========################### config.getServletContext().getServerInfo(): " + config.getServletContext().getServerInfo());		
		//System.out.println("==========################### config.getServletContext().getContextPath(): " + config.getServletContext().getContextPath());		

		log.info("Loading filter with ServletContextName"+ config.getServletContext().getServletContextName());
		
		// Print the init parameter
		log.info("Loading filter with param allowedUri="+allowedUri);
		
		String [] allowedUriArray = allowedUri.split(",");
		
		for (String uri : allowedUriArray) {
			//System.out.println("uri="+uri);
			String requestURI = config.getServletContext().getContextPath() + uri;
			allowedUriList.add(requestURI);
		}		

		log.info("Loading filter with allowedUriList="+allowedUriList.toString());
	}

	public void destroy() {
		// add code to release any resource
		this.allowedUriList = null;
	}
}
